package org.jeecg.common.util.spelutil;


import org.jeecg.common.util.SpringContextUtils;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;

import java.util.HashMap;
import java.util.Map;

import static cn.hutool.core.text.CharSequenceUtil.isBlank;

public class SpELUtils {

    public static Object evaluateExpression(String expression) {
        Object o = evaluateExpression(expression, Object.class);
        return o;
    }

    public static <T> T evaluateExpression(String expression, Class<T> resultType) {
        T t = evaluateExpression(null, new HashMap<>(), expression, resultType);
        return t;
    }

    public static <T> T evaluateExpression(Object rootObject, String expression, Class<T> resultType) {
        return evaluateExpression(rootObject, new HashMap<>(), expression, resultType);
    }

    public static <T> T evaluateExpression(Map<String, Object> variables, String expression, Class<T> resultType) {
        return evaluateExpression(null, variables, expression, resultType);
    }

    public static <T> T evaluateExpression(Object rootObject, Map<String, Object> variables, String expression, Class<T> resultType) {
        if (isBlank(expression)) {
            return null;
        }
        ExpressionParser parser = new SpelExpressionParser();
        StandardEvaluationContext ctx = new StandardEvaluationContext();
        ctx.setBeanResolver((context, beanName) -> SpringContextUtils.getBean(beanName));
        ctx.setVariables(variables);
        ctx.setRootObject(rootObject);
        T obj = parser.parseExpression(expression).getValue(ctx, resultType);
        return obj;
    }

    //    @ApiOperation("测试spel")
//    @GetMapping("testspel")
//    @PreventRepeatSubmit
    public Integer daiosoj(Integer i) {
        Integer integer = SpELUtils.evaluateExpression("@projectServiceImpl.testspel(1,2,3)", Integer.class);
//        Integer testspel = service.testspel(i);
        return integer;
    }


}
